<template>
  <div class="page-main">
    <query-page
      ref="queryPageRef"
      :key="activeTab"
      v-model:selectedKeys="selectedKeys"
      :form-component-config="formComponentConfig"
      :form-render-config="formRenderConfig"
      :form-render-keys="formRenderKeys"
      :table-component-config="tableComponentConfig"
      :table-render-config="tableRenderConfig"
      :table-render-keys="tableRenderKeys"
      :loading="isLoading"
      :data="renderData"
      :total="total"
      title="询价单生成-按货源"
      :row-selection-type="activeTab === '1' ? 'checkbox' : undefined"
      @query-data="getData"
      @row-click="rowclick"
    >
      <template #header-ext-container>
        <a-radio-group
          v-model="activeTab"
          type="button"
          class="radio-aras"
          @change="change"
        >
          <a-radio value="1">新增询价单</a-radio>
          <a-radio value="2">已生成询价单</a-radio>
        </a-radio-group>
      </template>
      <template #container-side>
        <template v-if="activeTab === '1'">
          <a-button
            v-permission="['procurement:plan-supplier:batchSave']"
            type="primary"
            :disabled="btnDisable"
            @click="handleCreate('batch')"
            >获取货源供应商</a-button
          >
          <a-button
            v-permission="['procurement:inquiry:createInquiry']"
            type="text"
            :disabled="btnDisable"
            @click="handelCreateInquiry()"
            >生成询价单</a-button
          >
          <a-button
            v-permission="['procurement:plan-list:updateInquiryStatus']"
            type="text"
            :disabled="btnDisable"
            @click="handelDraw('', 'batch')"
            >撤销询价</a-button
          >
        </template>
      </template>
      <template #operate="{ record }">
        <span
          v-permission="['procurement:plan-supplier:batchSave']"
          class="row-btn"
          @click="getPlanList(record.planListNo)"
          >货源供应商</span
        >
        <span
          v-permission="['procurement:plan-list:updatePlanForXjd:inquiry']"
          class="row-btn"
          :hidden="activeTab === '2'"
          @click="batchEdit(record)"
          >编辑</span
        >
        <span
          v-permission="['procurement:inquiry:createInquiry']"
          class="row-btn"
          :hidden="activeTab === '2'"
          @click="handelCreateInquiry(record.planListNo)"
          >生成询价单</span
        >
        <span
          v-permission="['procurement:plan-list:updateInquiryStatus']"
          class="row-btn"
          :hidden="activeTab === '2'"
          @click="handelDraw(record, 'row')"
          >撤销询价</span
        >
        <span
          v-permission="['procurement:inquiry:drawInquiry']"
          class="row-btn"
          :hidden="activeTab === '1'"
          @click="handelDrawInquiry(record.planListNo)"
          >撤回询价单</span
        >
      </template>
    </query-page>

    <!-- 子表单 -->
    <compflagbox
      v-if="inseflag"
      ref="compflagboxRef"
      :conte="listscontext"
      :activetabval="activeTab"
      :listtab="liststab"
      type="2"
      @get-datas="handelPlanListNo"
      @close-drawer="closeDrawer"
    >
    </compflagbox>
    <!-- 弹窗 -->
    <popUp
      v-if="popVisible"
      title-text="编辑"
      :width="500"
      @handle-ok="handleOk"
      @handle-cancel="handleCancel"
    >
      <template #content>
        <a-form ref="formRef" :model="form" :rules="formRules">
          <a-row :gutter="16">
            <a-col :span="20">
              <a-form-item
                field="inquiryQty"
                label="本次询价数量："
                label-col-flex="120px"
              >
                <a-input-number
                  v-model.number="form.inquiryQty"
                  :min="0"
                  placeholder="请输入"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </template>
    </popUp>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted, watch, nextTick } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { hasDataAndBack } from '@/common/utils/index';
  import queryPage from '@/common/components/query-page/index.vue';
  import {
    planList,
    planSupplier,
    planListNo,
    createInquiry,
    draw,
    drawInquiry,
    updatePlan,
  } from '@/api/supplier/inquiry-list-create';
  // import pageTitle from '@/common/components/title/page-title.vue';
  import { ObjKey } from '@/config/const';
  import { info } from '@/common/utils/modal-promise';
  import {
    formRenderConfig,
    formComponentConfig,
  } from './components/formComp/baseFormConfig';
  import {
    tableRenderConfig,
    tableComponentConfig,
  } from './components/tableComp/baseTableConfig';
  import { baseRenderKeys } from './components/baseDatainqlistcreate';
  import popUp from './components/pop-up.vue';
  import compflagbox from './components/compflag.vue';

  const total = ref(0);
  const queryPageRef = ref();
  const selectedKeys = ref([]);
  const planNo = ref('');
  const compflagboxRef = ref();
  const activeTab = ref('1');
  const isLoading = ref(true);
  const compflag = ref(false);
  const inseflag = ref(false);
  const popVisible = ref(false);
  const form = ref({
    inquiryQty: 0,
    id: '',
  });
  const planNos: any = ref([]);
  const formRules = ref({
    inquiryQty: [{ required: true, message: '请填写', trigger: 'blur' }],
  });
  const rowData: any = ref({});
  const renderData = ref<any[]>([]);
  const listscontext: any = ref([]);
  const liststab = ref({});
  const contentall = ref({
    person: '',
    time: '',
    department: '',
    remark: '',
  });
  // 渲染检索项
  const formRenderKeys = ref<any[]>([]);
  // 当前表格要渲染哪些值
  const tableRenderKeys = ref<any[]>([]);
  const btnDisable = ref(true);

  watch(
    selectedKeys,
    (n) => {
      if (n?.length > 0) {
        btnDisable.value = false;
        getPlanNo(n);
      } else {
        btnDisable.value = true;
      }
    },
    {
      deep: true,
    }
  );
  const getPlanNo = (n: any) => {
    planNos.value.length = 0;
    n.forEach((k: any) => {
      renderData.value.forEach((e: any) => {
        if (e.id === k) {
          planNos.value.push(e.planListNo);
        }
      });
    });
  };
  const getData = async (queryInfo: object) => {
    renderData.value = [];
    isLoading.value = true;
    const params = {
      inquiryStatus: activeTab.value,
      ...queryInfo,
    };
    const res = (await planList(params)) as any;
    if (res.code === 200) {
      renderData.value = res.data?.list;
      total.value = res.data.total;
      if (
        hasDataAndBack(
          renderData.value,
          total.value,
          queryPageRef.value?.getStatus().pageNo
        )
      ) {
        queryPageRef.value?.setCurrent(
          queryPageRef.value.getStatus().pageNo - 1
        );
        getData(queryPageRef.value?.getStatus());
      }
    }
    isLoading.value = false;
  };
  const change = () => {
    initData();
    getData(queryPageRef.value.getStatus());
  };
  const rowclick = (val: any) => {
    contentall.value.person = val.id;
    compflag.value = true;
  };
  const initData = () => {
    const tabConfig: ObjKey = {
      '1': 'newinquirysheet',
      '2': 'theinquirysheethasbeenconfirmed',
    };
    formRenderKeys.value =
      baseRenderKeys[tabConfig[activeTab.value]].formRenderKeys;
    tableRenderKeys.value =
      baseRenderKeys[tabConfig[activeTab.value]].newTableRenderKeys;
    liststab.value =
      baseRenderKeys[tabConfig[activeTab.value]].subformRenderKeys;
  };

  // 子表单取消
  const closeDrawer = () => {
    inseflag.value = false;
  };
  const batchEdit = async (record: any) => {
    popVisible.value = true;
    rowData.value.id = record.id;
    form.value.inquiryQty = record.inquiryQty;
  };
  // 弹窗确认
  const handleOk = async (flag: boolean) => {
    rowData.value.inquiryQty = form.value.inquiryQty;
    const res = (await updatePlan({
      id: rowData.value.id,
      inquiryQty: form.value.inquiryQty,
    })) as any;
    if (res.code === 200) {
      Message.success('保存成功');
      popVisible.value = flag;
      getData(queryPageRef.value.getStatus());
    }
  };
  // 获取供应商 planNo
  const handleCreate = (type: string, data?: any) => {
    const planArr: any = type === 'row' ? [data.planListNo] : planNos.value;
    handelPlanSupplier(planArr);
  };
  // 获取供应商
  const handelPlanSupplier = async (data: any) => {
    const res = (await planSupplier(data)) as any;
    if (res.code === 200) {
      Message.success('操作成功');
      selectedKeys.value.length = 0;
    }
  };
  // 获取列表当前 planNo
  const getPlanList = (data: any) => {
    planNo.value = data;
    handelPlanListNo();
  };
  const handelPlanListNo = async () => {
    const params = {
      planListNo: planNo.value,
    };
    const res = (await planListNo(params)) as any;
    if (res.code === 200) {
      listscontext.value = res.data?.list;
      inseflag.value = true;
      nextTick(() => {
        compflagboxRef.value.getData();
      });
    }
  };

  const handelCreateInquiry = async (plan?: any) => {
    await info({
      title: '提示',
      titleAlign: 'start',
      content: '您确定要将当前所选的数据生成询价单？',
      closable: true,
      modalClass: 'tips-modal',
      okText: '确认',
      hideCancel: false,
      cancelText: '取消',
    });
    const nolist: any = plan ? [plan] : planNos.value;
    const res = (await createInquiry(nolist)) as any;
    if (res.code === 200) {
      Message.success('操作成功');
      getData(queryPageRef.value.getStatus());
      selectedKeys.value.length = 0;
    }
  };
  // 撤销询价
  const handelDraw = async (row: any, type: string) => {
    const nolist: any = [];
    if (type === 'batch') {
      selectedKeys.value?.forEach((e: any) => {
        nolist.push({
          id: e,
          inquiryStatus: 0,
        });
      });
    } else {
      nolist.push({
        id: row.id,
        inquiryStatus: 0,
      });
    }
    await info({
      title: '提示',
      titleAlign: 'start',
      content: '您确定要撤销询价',
      closable: true,
      modalClass: 'tips-modal',
      okText: '确认',
      hideCancel: false,
      cancelText: '取消',
    });
    const res = (await draw(nolist)) as any;
    if (res.code === 200) {
      Message.success('操作成功');
      getData(queryPageRef.value.getStatus());
      selectedKeys.value.length = 0;
    }
  };
  // 撤销询价单
  const handelDrawInquiry = async (plan?: any) => {
    await info({
      title: '提示',
      titleAlign: 'start',
      content: '您确定要撤回询价单',
      closable: true,
      modalClass: 'tips-modal',
      okText: '确认',
      hideCancel: false,
      cancelText: '取消',
    });
    const nolist: any = plan ? [plan] : planNos.value;
    const res = (await drawInquiry(nolist)) as any;
    if (res.code === 200) {
      Message.success('操作成功');
      getData(queryPageRef.value.getStatus());
    }
  };
  // 弹窗取消
  const handleCancel = (flag: boolean) => {
    popVisible.value = flag;
  };

  watch(activeTab, () => {
    initData();
  });
  onMounted(() => {
    activeTab.value = '1';
    initData();
  });
</script>

<style lang="less" scoped>
  .row-btn {
    color: #1e89ff;
    cursor: pointer;
  }

  .radio-ara {
    display: flex;
    justify-content: space-between;
    width: 17.5%;
  }

  .radio-aras {
    width: 100%;
    margin-top: 16px;

    :deep(.arco-radio-button) {
      flex: 1;
      text-align: center;
    }
  }

  .rightcss {
    display: flex;
    flex-direction: column;
    padding: 16px;
  }

  .rightcss div {
    margin-bottom: 8px;
  }

  :deep(.arco-input-wrapper.arco-input-disabled) {
    border-radius: 5px;
  }

  :deep(.arco-btn-text.arco-btn-disabled) {
    color: var(--color-text-4) !important;
    background-color: var(--color-secondary-disabled) !important;
    border: 1px solid transparent !important;
    cursor: not-allowed !important;
  }

  :deep(.arco-btn-text) {
    margin-right: 8px;
    color: var(--color-text-2) !important;
    background-color: var(--color-secondary) !important;
    border: 1px solid transparent !important;
  }
</style>
